import * as cloudDb from '@agconnect/database-server';
import * as agc from '@agconnect/common-server';
import * as Utils from './utils/Utils.js';
import { CommentResp } from './model/CommentResp';
import { comment } from './model/comment';

const ZONE_NAME = "HarmonyOSDeveloper";

export class DatabaseHelper {
  logger;
  cloudDbZone;

  constructor(context, logger) {
    this.logger = logger;
    const credential = Utils.getCredential(context, logger);
    try {
      // 初始化AGCClient
      logger.info("begin to init agcClient");
      let agcClient;
      try {
        agcClient = agc.AGCClient.getInstance();
      } catch {
        agc.AGCClient.initialize(credential);
        agcClient = agc.AGCClient.getInstance();
      }
      // 初始化AGConnectCloudDB实例
      logger.info("begin to init cloudDb");
      let cloudDbInstance;
      try {
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      } catch {
        cloudDb.AGConnectCloudDB.initialize(agcClient);
        cloudDbInstance = cloudDb.AGConnectCloudDB.getInstance(agcClient);
      }
      // 创建CloudDBZoneConfig配置对象，并设置云侧CloudDB zone名称，打开Cloud DB zone实例
      const cloudDBZoneConfig = new cloudDb.CloudDBZoneConfig(ZONE_NAME);
      this.cloudDbZone = cloudDbInstance.openCloudDBZone(cloudDBZoneConfig);
    } catch (err) {
      logger.error("init CloudDBZoneWrapper error: " + err);
    }
  }

  async queryComment(pathId) {
    let resList = [];
    if (!this.cloudDbZone) {
      console.log("CloudDBClient is null, try re-initialize it");
      return;
    }
    try {
      const commentQuery = cloudDb.CloudDBZoneQuery.where(comment).orderByDesc("create_time");
      commentQuery.equalTo('path_id', pathId)
      const queryResp = await this.cloudDbZone.executeQuery(commentQuery);
      let commentData = queryResp.getSnapshotObjects();
      this.logger.info("commentQuery success ");
      console.log('commentData=>', commentData);
      if (commentData.length <= 0) {
        return [];
      }
      if (commentData.length > 0) {
        for (let i = 0; i < commentData.length; i++) {
          let dataQ: comment = commentData[i];
          resList.push(new CommentResp()(
            dataQ.getId(),
            dataQ.getPath_id(),
            dataQ.getUsername(),
            dataQ.getCreate_time(),
            dataQ.getPath_name(),
            dataQ.getComment(),
            dataQ.getScore(),
          ))
        }
      }
    } catch (error) {
      this.logger.info("query comment error " + error);
    } finally {
      return resList;
    }
    return resList;
  }
}